#!/usr/bin/env python
#    This file is part of django_ip2country.
#    django_ip2country is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    django_ip2country is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with django_ip2country.  If not, see <http://www.gnu.org/licenses/>.
#    Author: Esteban Feldman esteban.feldman@gmail.com


import csv
import os
import sys
from optparse import OptionParser

from django.conf import settings
from django_ip2country import models


def main():
    if not 'DJANGO_SETTINGS_MODULE' in os.environ:
        print 'DJANGO_SETTINGS_MODULE should be set, exiting.'
        sys.exit(0)
    usage = "usage: %prog -p PATH_TO_DB | --path=PATH_TO_DB"
    parser = OptionParser(usage)
    parser.add_option('-p', '--path', dest='db_path',
                      help="The path to the project directory.")
    (options, args) = parser.parse_args()
    
    
    if settings.DATABASE_ENGINE is 'sqlite3':
        if not options.db_path:
            parser.error("You must specify the project directory path.")
    
        project_dir = os.path.abspath(options.db_path) # or path to the dir. that the db should be in.
        settings.DATABASE_NAME = os.path.join( project_dir, settings.DATABASE_NAME )
    
    CSV_FILE = 'ip-to-country.csv'
    
    # delete all objects
    print 'This will take a while, so sit back and relax.'
    models.Ip2Country.objects.all().delete()
    
    reader = csv.reader(open(CSV_FILE))
    count = 0    
    for ipf, ipt, cc2, cc3, cname in reader:
        count += 1          
        object = models.Ip2Country(count,ipf, ipt, cc2, cc3, cname)
        object.save()
        if count % 10000 == 0:
            print count
    print count , "inserted. :)"
    del reader

if __name__ == '__main__':
    main()
